<template>
  <div>
    <a-input
      v-if="input"
      @click="visible = true"
      :value="checkedText"
      :read-only="true"
      @focus="(evt) => evt.target.blur()"
    >
      <a-icon slot="prefix" :type="type == 'user' ? 'user' : 'team'" />
      <a-tooltip slot="suffix" title="清除">
        <a-icon type="close-circle" style="color: rgba(0, 0, 0, 0.45)" @click="clear" />
      </a-tooltip>
    </a-input>
    <a-button v-else type="primary" @click="visible = true" icon="plus">添加用户</a-button>
    <a-modal
      destroyOnClose
      title="案件分派"
      :visible="visible"
      :bodyStyle="{ height: '50vh' }"
      @cancel="close"
      width="30%"
    >
      <template slot="footer">
        <a-button key="back" @click="close"> 取消 </a-button>
        <a-button key="submit" type="primary" @click="save"> 确定 </a-button>
      </template>
      <a-row>
        <a-col :span="24" style="height: 45vh; overflow: auto">
          <a-input-search style="margin-bottom: 8px" placeholder="请输入名称" @change="onChange" />
          <a-tree
            v-if="treeData"
            :replaceFields="{ children: 'children', title: 'name', key: 'id' }"
            :checkable="multiple"
            :tree-data="treeData"
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            @expand="onExpand"
            @select="onSelect"
            @check="onCheck"
            :default-checked-keys="default_checked_keys"
            :defaultSelectedKeys="default_selected_seys"
            :checkStrictly="true"
            showIcon
          >
            <template slot="title" slot-scope="{ name, type, total, isApplyname, isTargetname }">
              <!-- 部门 -->
              <template v-if="type == 'depart'">
                <span class="depart_text node_text">{{ name }}</span>
              </template>
              <!-- 人员 -->
              <template v-else-if="type == 'user'">
                <span class="node_text">
                  {{ `${name}（在办案件数：${total}）` }}
                  <span class="tag_area" v-if="isApplyname" color="green"> 相同申请人 </span>
                  <span class="tag_area" v-else-if="isTargetname" color="green"> 相同被申请人 </span></span
                >
              </template>
              <!-- 案子 -->
              <template v-else-if="type == 'case'">
                <span :class="isApplyname == 3200 || isTargetname == 3200 ? 'case_active_text' : ''">{{ name }}</span>
              </template>
            </template>

            <!-- 自定义图标 覆盖展开图标 -->
            <template slot="custom" slot-scope="{ type, id }">
              <div
                v-if="expandedKeys.includes(id) && ['depart', 'user'].includes(type)"
                class="custom-icon-fold algin_justity_center"
              >
                －
              </div>
              <div
                v-else-if="!expandedKeys.includes(id) && ['depart', 'user'].includes(type)"
                class="custom-icon-open algin_justity_center"
              >
                ＋
              </div>
            </template>

            <!-- 展开图标作用域插槽 -->
            <template slot="switcherIcon">
              <div class="icon-add">＋</div>
            </template>
          </a-tree>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>

<script>
import { queryBusineTree } from '@/api/apply/apl_main.js'
import { quyeryTreeData } from '@/api/base/ha_depart'

const getParentKey = (id, tree) => {
  let parentKeys = []
  var forFn = function (arr, id) {
    for (let i = 0; i < arr.length; i++) {
      const node = arr[i]
      if (node.id === id) {
        parentKeys.push(id)
        forFn(tree, node.parentid)
        break
      } else {
        node.children && forFn(node.children, id)
      }
    }
  }
  forFn(tree, id)
  return parentKeys
}
const dataList = [] // 所有书节点的id
const generateList = (data) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i]
    const id = node.id
    const name = node.name
    const parentid = node.pid
    let arr = dataList.filter((item) => {
      return item.id == id
    })
    if (arr.length > 0) {
      continue
    }
    dataList.push({ id, name, parentid })
    if (node.children) {
      generateList(node.children)
    }
  }
}
export default {
  props: {
    applyid: {
      type: String,
      require: true,
    },
    // 指定父节点
    departId: {
      type: Number,
      default: null,
    },
    type: {
      // 是否禁用部门
      type: String,
      default: 'depart',
    },
    multiple: {
      // 开启多选框
      type: Boolean,
      default: false,
    },
    value: {
      // 默认勾选中的
      default: null,
    },
    text: {
      // 文本框默认显示文字
      default: null,
    },
    input: {
      // 显示文本框
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      visible: false,
      treeData: [],
      expandedKeys: [], // 展开指定的树节点
      searchValue: '', // 搜索值
      autoExpandParent: true, // 是否自动展开父节点
      default_checked_keys: [], // 默认勾中的值
      default_selected_seys: [], // 默认选中的值
      checkedText: '', // 默认显示的值
      obj: {}, // 单选返回Object
      arr: [], // 多选返回[Object]
    }
  },
  async created() {
    // 默认展开指定节点
    this.departId && this.expandedKeys.push(String(this.departId))
    await this.findTreeData()
    // 初始化默认勾选的节点
    if (this.multiple) {
      this.default_checked_keys = this.value || []
    } else {
      this.default_selected_seys = this.value || []
    }
    this.checkedText = this.text
  },
  methods: {
    save() {
      this.searchValue = ''
      if (this.multiple) {
        if (this.arr.length === 0) {
          this.$message.error(`请选择${this.type === 'user' ? '用户' : '部门'}`)
          return
        }
        console.log('arr', this.arr)
        this.checkedText = this.arr.map((m) => m.name).toString()
        this.default_checked_keys = this.arr.map((m) => m.id)
        this.$emit('save', this.arr)
      } else {
        if (Object.keys(this.obj).length === 0) {
          this.$message.error(`请选择${this.type === 'user' ? '用户' : '部门'}`)
          return
        }
        this.checkedText = this.obj.name
        this.default_selected_seys = [this.obj.id]
        this.$emit('save', this.obj)
      }
      this.visible = false
    },
    close() {
      this.searchValue = ''
      this.visible = false
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onChange(e) {
      const value = e.target.value
      let parentkeys = []
      if (value) {
        dataList.forEach((item) => {
          if (item.name.indexOf(value) > -1) {
            if (item.id.startsWith('dept_id')) {
              parentkeys.push(...getParentKey(item.id, this.treeData))
            } else {
              parentkeys.push(...getParentKey(item.parentid, this.treeData))
            }
          }
        })
      }
      Object.assign(this, {
        expandedKeys: parentkeys,
        searchValue: value,
        autoExpandParent: true,
      })
    },
    /**
     * 单选
     */
    onSelect(selectedKeys, e) {
      let obj = {}
      if (e.selected) {
        let data = e.node.dataRef
        obj.id = data.id
        obj.name = data.name
        obj.parentid = data.parentid
        obj.type = this.type
        if (this.type === 'user') obj.avatar = data.scopedSlots.avatar
      } else {
        obj.id = ''
        obj.name = ''
        obj.parentid = ''
        obj.type = this.type
        if (this.type === 'user') obj.avatar = ''
      }
      this.obj = obj
      this.$emit('select', this.obj)
    },
    /**
     * 多选框
     */
    onCheck(checkedKeys, e) {
      if (e.checkedNodes.length > 0) {
        let arr = []
        e.checkedNodes.forEach((v) => {
          let data = v.data.props.dataRef
          let obj = {}
          obj.id = data.id
          obj.name = data.name
          obj.parentid = data.pid
          obj.type = this.type
          if (this.type == 'user') obj.avatar = data.scopedSlots.avatar
          arr.push(obj)
        })
        this.arr = arr
      } else {
        this.arr = []
      }
      this.$emit('change', this.arr)
    },
    /**
     * 异步加载部门员工
     */
    onLoadData(treeNode) {
      return new Promise((resolve) => {
        getDeptUser({
          departid: treeNode.dataRef.id,
        }).then((res) => {
          if (res.code == 0) {
            if (res.data && res.data.length > 0) {
              if (treeNode.dataRef.children == null) {
                treeNode.dataRef.children = []
              }
              res.data.forEach((v) => {
                v.isLeaf = true
                v.scopedSlots = { title: 'title', type: 'user', icon: 'custom' }
                treeNode.dataRef.children.push(v)
              })
            }
            this.treeData = [...this.treeData]
            resolve()
          }
        })
      })
    },
    // 给树数据中的部门添加禁选属性
    renderTreeNodes(data) {
      const setData = data.map((item) => {
        // 根据名称进行排序
        if (item.children && item.children.length > 0) {
          item.children = item.children.sort(function (a, b) {
            return a.name.localeCompare(b.name)
          })
        }
        if (item.type !== this.type) {
          item.disabled = true
        }
        item.children && this.renderTreeNodes(item.children)
        return item
      })
      return setData
    },
    // 查询树下拉的数据
    findTreeData() {
      if (this.type === 'depart') {
        quyeryTreeData({ parent: this.departId }).then((res) => {
          if (res.code === 0 && res.data) {
            generateList(res.data)
            this.treeData = this.renderTreeNodes(res.data)
          }
        })
      } else if (this.type === 'user') {
        queryBusineTree(this.applyid, this.departId).then((res) => {
          if (res.code === 0 && res.data) {
            let data = res.data
            data = this.fixSlot(data)
            generateList(data)
            this.treeData = this.renderTreeNodes(data)
          }
        })
      }
    },
    clear() {
      this.checkedText = ''
      this.default_checked_keys = []
      this.default_selected_seys = []
      this.arr = []
      this.obj = {}
      this.searchValue = ''
      if (this.multiple) {
        this.$emit('save', this.arr)
      } else {
        this.$emit('save', this.obj)
      }
    },
    fixSlot(data) {
      // 构造slot
      return data.map((item) => {
        item.scopedSlots = { avatar: item.avatar, title: 'title', icon: 'custom' }
        if (item.type === 'user') {
          if (item.children) {
            item.children = this.fixSlot(item.children)
          }
        } else {
          if (item.children) {
            item.children = this.fixSlot(item.children)
          }
        }
        return item
      })
    },
  },
}
</script>

<style scoped>
::v-deep .ant-tree-node-content-wrapper span {
  color: #2c2c2c;
}
/* 禁用状态文字 */
::v-deep li.ant-tree-treenode-disabled > .ant-tree-node-content-wrapper span {
  color: #2c2c2c;
}

.depart_text {
  font-weight: 800;
  font-size: 15px;
}
/* 匹配的案子样式 */
.case_active_text {
  color: rgb(75, 163, 235) !important;
}

/* 相同申请人样式 */
.tag_area {
  border: 1px solid red;
  padding: 0 10px;
  color: #de0000 !important;
  border-radius: 10px;
}

.custom-icon-open,
.custom-icon-fold,
.icon-add {
  color: #fff;
  background-color: #0072c6;
  font-weight: 800;
  font-size: 16px !important;
}
/* 用文字图标覆盖展开图标实现效果 */
.custom-icon-open,
.custom-icon-fold {
  width: 20px;
  height: 20px;
  margin-left: -26px;
}
/* 文字偏移补充图标间距 */
.node_text {
  margin-left: -26px;
}
/* 折叠样式 */
.custom-icon-fold {
  background-color: #09c89f;
}
/* 自定义展开图标 */
.icon-add {
  width: 24px;
  height: 24px;
  opacity: 0;
}
</style>
